<?php

namespace app\common\controller;

use think\Controller;

require_once APP_PATH . '/../vendor/aliyuncs/oss-sdk-php/autoload.php';
use OSS\Core\OssException;
use OSS\OssClient;

class AliOss
{
    public static function uploadFile($mulu, $file, $filetype = 1)
    {
        $type = pathinfo($file['name'], PATHINFO_EXTENSION);
        if ($filetype == 1) {
            if (!in_array($type, ['jpg', 'png', 'gif', 'jpeg', 'mp4', 'flv'])) {
                $arr = ['status' => 0, 'msg' => '非法操作'];
                return $arr;
            }

            $upload = new \think\File($file['tmp_name']);
            $hash = $upload->hash();
            $pic = Db('picture')->where('sha1', $hash)->find();
        }


//        if ($pic) {
//            $data = [
//                'id' => $pic['id'],
//                'path' => $pic['path']
//            ];
//            return ['status' => 200, 'msg' => '上传成功', 'data' => $data];
//        }

        try {
            $KeyId = config('alioss.KeyId');
            $KeySecret = config('alioss.KeySecret');
            $EndPoint = config('alioss.EndPoint');
            $Bucket = config('alioss.Bucket');

            //实例化
            $ossClient = new OssClient($KeyId, $KeySecret, $EndPoint);
            //sha1加密 生成文件名 连接后缀

            $fileName = $mulu . '/' . sha1(date('YmdHis', time()) . uniqid()) . '.' . $type;
            //执行阿里云上传
            $result = $ossClient->uploadFile($Bucket, $fileName, $file['tmp_name']);
            //图片地址:$result['info']['url']

            if ($filetype == 1) {
                $pdata = [
                    'path' => $result['info']['url'],
                    'sha1' => $hash,
                    'status' => 1,
                    'create_time' => time()
                ];
                Db('picture')->insert($pdata);
                $id = Db('picture')->getLastInsID();
                $data = [
                    'id' => $id,
                    'path' => $result['info']['url']
                ];
            } else {
                $data = [
                    'path' => $result['info']['url']
                ];
            }

            $arr = ['status' => 200, 'msg' => '上传成功', 'data' => $data];
        } catch (OssException $e) {
            $arr = ['status' => 0, 'msg' => $e->getMessage(), 'data' => ''];
        }
        return $arr;
    }
}